﻿using EMoney.IStock.Client.DataAccess.HD;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.HD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using EMoney.IStock.Client.Business.MC;
using EMoney.IStock.Client.Models.MC;

namespace EMoney.IStock.Client.Business.HD
{
    /// <summary>
    /// 互动业务处理类
    /// </summary>
    public class HDBll
    {
        private object objTopic = new object();
        private object objReply = new object();
        private object objRecentReply = new object();

        /// <summary>
        /// 最近问答缓存KEY
        /// </summary>
        private const string RECENTREPLY_CACHED_KEY = "EMoney.IStock.Client.Business.HD.RecentReply";
        /// <summary>
        /// 我的问答
        /// </summary>
        private const string MYREPLY_CACHED_KEY = "EMoney.IStock.Client.Business.HD.MyReply";
        /// <summary>
        /// 提问信息缓存KEY
        /// </summary>
        private const string TOPIC_CACHED_KEY = "EMoney.IStock.Client.Business.HD.Topic";
        /// <summary>
        /// 回复信息缓存KEY
        /// </summary>
        private const string REPLY_CACHED_KEY = "EMoney.IStock.Client.Business.HD.Reply";

        /// <summary>
        /// 新增提问
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="userid">用户编号</param>
        /// <param name="channelid">频道编号</param>
        /// <returns></returns>
        public bool AddTopic(string title,string content,int userid,int channelid)
        {
            bool ret = false;

            try
            {                
                TopicDal dal = new TopicDal();

                if (dal.AddTopic(new Topic()
                {
                    title = title,
                    topiccontent = content,
                    authorid = userid,
                    channelid = channelid
                }) == 1)
                {
                    ret = true;

                    string key = string.Concat(MYREPLY_CACHED_KEY, ".", userid, ".", channelid);

                    CacheManager.DefaultCache.Remove(key);  //清空我的问答
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "新增提问失败");
            }

            return ret;
        }

        /// <summary>
        /// 获取回复信息
        /// </summary>
        /// <param name="replyID"></param>
        /// <returns></returns>
        private Reply GetReply(int topicid)
        {
            string key = string.Concat(REPLY_CACHED_KEY, ".", topicid);

            Reply reply = CacheManager.DefaultCache.Get<Reply>(key);

            if (reply == null)
            {
                try
                {
                    lock (objReply)
                    {
                        reply = CacheManager.DefaultCache.Get<Reply>(key);

                        if (reply == null)
                        {
                            ReplyDal replyDal = new ReplyDal();

                            reply = replyDal.GetReply(topicid);

                            if (reply == null)
                            {
                                reply = new Reply();
                            }

                            CacheManager.DefaultCache.Set<Reply>(key, reply);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, string.Concat("获取回复信息失败.", topicid));
                }
            }

            return reply;
        }

        /// <summary>
        /// 获取提问信息
        /// </summary>
        /// <param name="topicID"></param>
        /// <returns></returns>
        private Topic GetTopic(int topicID)
        {
            string key = string.Concat(TOPIC_CACHED_KEY, ".", topicID);

            Topic topic = CacheManager.DefaultCache.Get<Topic>(key);

            if (topic == null)
            {
                try
                {
                    lock (objTopic)
                    {
                        topic = CacheManager.DefaultCache.Get<Topic>(key);

                        if (topic == null)
                        {
                            TopicDal topicDal = new TopicDal();

                            topic = topicDal.GetTopic(topicID);

                            if (topic != null)
                            {
                                CacheManager.DefaultCache.Set<Topic>(key, topic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, string.Concat("获取提问信息失败.", topicID));
                }
            }

            if (topic != null)
            {
                topic.Reply = GetReply(topic.topicid);

                topic.timeshow = StringHelper.FormatDateTimeNew(topic.lasttime);

                if (topic.Reply != null && topic.Reply.topicid == topic.topicid)
                {
                    topic.Reply.timeshow = StringHelper.FormatDateTimeNew(topic.Reply.replytime);
                }

                MyInfoBll myInfoBll = new MyInfoBll();

                MC_MyInfo myInfo = myInfoBll.GetMyInfo(topic.authorid);

                if (myInfo != null)
                {
                    topic.username = myInfo.UserName;
                    topic.usernameshow = StringHelper.StringSubstrLen(myInfo.UserName, 10);
                    topic.userpicurl = myInfoBll.GetUserPic(77, myInfo.UserPic);
                }
            }

            return topic;
        }

        /// <summary>
        /// 最近问答
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="channelid">频道编号</param>
        /// <returns></returns>
        public string RecentReply(int userid, int channelid)
        {
            string ret = string.Empty;

            try
            {
                string key = string.Concat(RECENTREPLY_CACHED_KEY, ".", channelid);

                List<RecentReply> listReply = CacheManager.DefaultCache.Get<List<RecentReply>>(key);

                if (listReply == null)
                {
                    lock (objRecentReply)
                    {
                        listReply = CacheManager.DefaultCache.Get<List<RecentReply>>(key);

                        if (listReply == null)
                        {
                            ReplyDal replyDal = new ReplyDal();

                            listReply = replyDal.GetRecentReply(channelid);

                            if (listReply == null)
                            {
                                listReply = new List<RecentReply>();
                            }

                            CacheManager.DefaultCache.Set<List<RecentReply>>(key, listReply, 60 * 10);
                        }
                    }
                }

                if (listReply != null && listReply.Count > 0)
                {
                    listReply = listReply.FindAll(lst => lst.SpecificUserID == 0 || lst.SpecificUserID == userid);  //所有用户可见及当前用户可见的最近问答

                    if (listReply != null && listReply.Count > 0)
                    {
                        listReply = listReply.AsQueryable().OrderBy("ReplyTime desc").ToList();

                        //此处分页代码...

                        List<Topic> listTopic = new List<Topic>();

                        foreach (RecentReply recentReply in listReply)
                        {
                            listTopic.Add(GetTopic(recentReply.TopicID));   //问答信息
                        }

                        if (listTopic != null && listTopic.Count > 0)
                        {
                            ret = JsonHelper.ToJson(listTopic);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("获取最近问答失败.", userid, ".", channelid));
            }

            return ret;
        }

        /// <summary>
        /// 我的问答
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <param name="userid">频道编号</param>
        /// <returns></returns>
        public string MyTopic(int userid,int channelid)
        {
            string ret = string.Empty;

            try
            {
                string key = string.Concat(MYREPLY_CACHED_KEY, ".", userid, ".", channelid);

                List<MyTopic> listMyTopic = CacheManager.DefaultCache.Get<List<MyTopic>>(key);

                if (listMyTopic == null)
                {
                    TopicDal topicDal = new TopicDal();

                    listMyTopic = topicDal.GetMyTopic(userid, channelid);   //获取我的提问编号及最后修改时间

                    if (listMyTopic == null)
                    {
                        listMyTopic = new List<MyTopic>();
                    }

                    CacheManager.DefaultCache.Set<List<MyTopic>>(key, listMyTopic, 60 * 10);
                }

                if (listMyTopic != null && listMyTopic.Count > 0)
                {
                    listMyTopic = listMyTopic.AsQueryable().OrderBy("lasttime desc").ToList();

                    //此处分页代码...

                    List<Topic> listTopic = new List<Topic>();

                    foreach (MyTopic mytopic in listMyTopic)
                    {
                        listTopic.Add(GetTopic(mytopic.TopicID));   //问答信息
                    }

                    if (listTopic != null && listTopic.Count > 0)
                    {
                        ret = JsonHelper.ToJson(listTopic);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("获取我的问答失败.", userid, ".", channelid));
            }

            return ret;
        }

        /// <summary>
        /// 赞成、反对投票
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="topicid"></param>
        /// <param name="topicid"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public string Vote(int userid, int topicid, int replyid, int flag)
        {
            string ret = string.Empty;

            try
            {
                Reply reply = GetReply(topicid);

                if (reply == null || reply.replyid != replyid)
                {
                    return string.Empty;
                }

                VoteDal voteDal = new VoteDal();

                if (voteDal.GetUserVoteCount(replyid, userid) == 0) //未投票过
                {
                    if (voteDal.AddVote(new Vote()
                    {
                        Flag = flag,
                        Replyid = replyid,
                        Userid = userid
                    }) == 1)
                    {
                        ret = "1";  //投票成功

                        ReplyDal replyDal = new ReplyDal();

                        switch (flag)
                        {
                            case 0:
                                replyDal.UpdateNoCount(replyid);
                                break;
                            case 1:
                                replyDal.UpdateYesCount(replyid);
                                break;
                            default:
                                break;
                        }

                        string key = string.Concat(REPLY_CACHED_KEY, ".", reply.topicid);

                        CacheManager.DefaultCache.Remove(key);
                    }
                }
                else
                {
                    ret = "-1"; //已投票过
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("投票失败.", userid, ".", replyid, ".", flag));
            }

            return ret;
        }

        /// <summary>
        /// 删除提问极其回复
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="topicid"></param>
        /// <returns></returns>
        public string Delete(int userid, int topicid, int channelid)
        {
            string ret = string.Empty;

            try
            {
                TopicDal topicDal = new TopicDal();

                Topic topic = topicDal.GetTopic(topicid);

                if (topic != null && topic.authorid == userid)
                {
                    ReplyDal replyDal = new ReplyDal();

                    replyDal.DeleteReply(topicid);
                    topicDal.DeleteTopic(topicid);

                    //清除我的提问缓存
                    string key = string.Concat(MYREPLY_CACHED_KEY, ".", userid, ".", channelid);

                    List<MyTopic> listMyTopic = CacheManager.DefaultCache.Get<List<MyTopic>>(key);

                    if (listMyTopic != null && listMyTopic.Count > 0)
                    {
                        MyTopic myTopic = listMyTopic.Find(lst => lst.TopicID == topicid);

                        if (myTopic != null)
                        {
                            listMyTopic.Remove(myTopic);

                            if (listMyTopic != null && listMyTopic.Count > 0)
                            {
                                CacheManager.DefaultCache.Set<List<MyTopic>>(key, listMyTopic, 60 * 10);
                            }
                            else
                            {
                                CacheManager.DefaultCache.Remove(key);
                            }
                        }
                    }

                    //清除最近问答缓存
                    key = string.Concat(RECENTREPLY_CACHED_KEY, ".", channelid);

                    List<RecentReply> listReply = CacheManager.DefaultCache.Get<List<RecentReply>>(key);

                    if (listReply != null && listReply.Count > 0)
                    {
                        RecentReply recentReply = listReply.Find(lst => lst.TopicID == topicid);

                        if (recentReply != null)
                        {
                            listReply.Remove(recentReply);

                            if (listReply != null && listReply.Count > 0)
                            {
                                CacheManager.DefaultCache.Set<List<RecentReply>>(key, listReply, 60 * 10);
                            }
                            else
                            {
                                CacheManager.DefaultCache.Remove(key);
                            }
                        }
                    }

                    CacheManager.DefaultCache.Remove(string.Concat(REPLY_CACHED_KEY, ".", topicid));
                    CacheManager.DefaultCache.Remove(string.Concat(TOPIC_CACHED_KEY, ".", topicid));

                    ret = "1";
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("删除提问极其回复失败.", userid, ".", topicid));
            }

            return ret;
        }
    }
}
